module.exports = function(sequelize, DataTypes) {
  var Notification = sequelize.define(
    'Notification',
    {
      id: {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true
      },
      formId: {
        type: DataTypes.STRING(20),
        comments: 'Get from WeChat, used for pushing template messages'
      },
      openId: {
        type: DataTypes.STRING(100),
        comments: 'User openId from WeChat, used for pushing template messages'
      },
      scope: {
        type: DataTypes.ENUM('task', 'progress', 'answer', 'document')
      }
    },
    {
      tableName: 'notifications',
      paranoid: true,
      indexes: [
        {
          name: 'created_at_idx',
          fields: ['createdAt']
        },
        {
          name: 'deleted_at_idx',
          fields: ['deletedAt']
        },
        {
          name: 'open_id_idx',
          fields: ['openId']
        },
        {
          name: 'user_id_idx',
          fields: ['userId']
        },
        {
          name: 'scoped_id_idx',
          fields: ['scope', 'targetId', 'userId']
        }
      ],
      comments: 'Notifications for template message'
    }
  )

  Notification.associate = function(models) {
    this.belongsTo(models.User, {
      as: 'Owner',
      foreignKey: 'userId',
      constraints: false
    })
    models.Task.hasMany(this, {
      foreignKey: 'targetId',
      constraints: false,
      scope: {
        scope: 'task'
      }
    })
    this.belongsTo(models.Task, {
      foreignKey: 'targetId',
      scope: {
        scope: 'task'
      },
      constraints: false
    })
    models.Progress.hasMany(this, {
      foreignKey: 'targetId',
      constraints: false,
      scope: {
        scope: 'progress'
      }
    })
    this.belongsTo(models.Progress, {
      foreignKey: 'targetId',
      scope: {
        scope: 'progress'
      },
      constraints: false
    })
    models.Answer.hasMany(this, {
      foreignKey: 'targetId',
      constraints: false,
      scope: {
        scope: 'answer'
      }
    })
    this.belongsTo(models.Answer, {
      foreignKey: 'targetId',
      scope: {
        scope: 'answer'
      },
      constraints: false
    })
    models.Document.hasMany(this, {
      foreignKey: 'targetId',
      constraints: false,
      scope: {
        scope: 'document'
      }
    })
    this.belongsTo(models.Document, {
      foreignKey: 'targetId',
      scope: {
        scope: 'document'
      },
      constraints: false
    })
  }
  return Notification
}
